package com.wt.springboot.demo.myendpoint;

import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author wangtao
 * @date 2023/2/27 20:09
 **/
public class MyEndpointHandlerAdapter implements HandlerAdapter, Ordered {

    @Override
    public boolean supports(Object handler) {
        // 只处理handler是MyEndpointHandlerMethod的
        return handler instanceof MyEndpointHandlerMethod;
    }

    @Override
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MyEndpointHandlerMethod handlerMethod = (MyEndpointHandlerMethod) handler;
        // 调用对应的方法获结果
        Object ret = handlerMethod.getMethod().invoke(handlerMethod.getBean());
        // 结果写回response的输出流
        response.getOutputStream().write(ret.toString().getBytes(StandardCharsets.UTF_8));
        return null;
    }

    @Override
    public long getLastModified(HttpServletRequest httpServletRequest, Object o) {
        return -1L;
    }

    @Override
    public int getOrder() {
        // 设置最高优先级
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
